<template>
  <div
    class="flex home flex-col h-100 gr-2"
    :class="{ 'text-selected-none': dragging }"
    @dragover="dragover"
    @drop="drop"
  >
    <HeadVue></HeadVue>
    <div class="flex-1 flex gc-4 pc">
      <SidebarVue></SidebarVue>
      <MainVue></MainVue>
    </div>
  </div>

  <Create></Create>
  <MessageVue></MessageVue>
  <Notify></Notify>
  <Welcome></Welcome>
  <BrowserVue></BrowserVue>
</template>

<script setup lang="ts">
  import { onMounted } from 'vue';
  import { programData } from '@/store/program/utils';
  import { toText } from '@/utils/file';
  import { ProgramData } from '@/store/program/types';
  import HeadVue from './head/Head.vue';
  import SidebarVue from './sidebar/Sidebar.vue';
  import MainVue from './main/Main.vue';
  import Create from './components/create/Create.vue';
  import MessageVue from './components/message/Message.vue';
  import hotkeys from './hotkey';
  import Notify from './components/notify/Notify.vue';
  import BrowserVue from './browser/Browser.vue';
  import { dragover } from './main/data/drag';
  import { notify } from './components/notify/bus';
  import { dragging } from './bus';
  import Welcome from './welcome/Welcome.vue';

  onMounted(() => {
    hotkeys.init();
  });
  /* 文件处理 */
  const drop = async (e: DragEvent) => {
    e.preventDefault();
    const files = e.dataTransfer?.files;
    if (files) {
      const asyncMap = Array.from(files).map(async (file) => {
        const text = await toText(file);
        return text;
      });
      const configs = await Promise.all(asyncMap);

      const data = programData();
      const repeatList: ProgramData[] = [];
      configs.forEach((json) => {
        const config = JSON.parse(json);
        const target = data.programList.find((m) => {
          if (m.title === config.title && m.id === config.id) {
            return m;
          }
          return null;
        });
        if (target) {
          repeatList.push(config);
        } else {
          data.programList.push(config);
        }
      });
      if (repeatList.length > 0) {
        notify({
          title: '是否覆盖',
          msg: `有${repeatList.length}个重复项,点击确认覆盖,否则取消导入`,
          onComfirm() {
            repeatList.forEach((item) => {
              data.programList.push(item);
            });
          },
        });
      }
    }
  };
</script>

<style lang="scss" scoped>
  .home {
    height: 100vh;
  }
</style>
